<template>
  <view class="income-details-container">
    <status-bar></status-bar>
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="back-btn" @click="goBack">
        <image src="/static/images/icon/backward_flat.png" class="back-icon-img"></image>
      </view>
      <view class="nav-title">收支明细</view>
    </view>
    
    <!-- 时间区间选择 -->
    <view class="date-picker-container">
      <uni-datetime-picker
        v-model="dateRange"
        type="daterange"
        rangeSeparator="至"
        @change="dateRangeChange"
        :border="false"
        :clearIcon="true"
        :start="startDate"
        :end="endDate"
        startPlaceholder="开始日期"
        endPlaceholder="结束日期"
      />
    </view>
    
    <!-- 收支统计区域 -->
    <view class="income-stats" v-if="false">
      <view class="stats-item">
        <text class="stats-label">收入</text>
        <text class="stats-value income-value">¥ {{totalIncome}}</text>
      </view>
      <view class="stats-item">
        <text class="stats-label">支出</text>
        <text class="stats-value expense-value">¥ {{totalExpense}}</text>
      </view>
    </view>
    
    <!-- 收支明细列表（带下拉刷新和上拉加载） -->
    <scroll-view 
      scroll-y 
      class="income-list"
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      refresher-background="#f5f5f5"
    >
      <!-- 明细项目 -->
      <view class="record-item" v-for="(item, index) in incomeList" :key="index">
        <view class="record-info">
          <view class="record-amount">{{item.transactionDescription}}</view>
          <view class="record-date">{{item.transactionTime}}</view>
        </view>
        <view class="record-status" :class="{'income-amount':  item.transactionType ==2 , 'expense-amount': item.transactionType == 1}">
          ¥ {{item.transactionAmount}}
          <view class="record-reason">余额: ¥ {{item.accountBalance}}</view>
        </view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state">
        <uni-load-more :status="loadMoreStatus"></uni-load-more>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { selectIncomeExpenseList } from '@/api/app/master/transactionlog.js'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more.vue'

export default {
  components: {
    uniLoadMore
  },
  onLoad() {
    // 页面加载时获取收支明细数据
    this.loadRecords();
  },
  data() {
    const currentDate = new Date()
    const currentYear = currentDate.getFullYear()
    const currentMonth = currentDate.getMonth() + 1
    
    // 计算默认的日期范围：当前月的第一天到最后一天
    const firstDay = new Date(currentYear, currentMonth - 1, 1)
    const lastDay = new Date(currentYear, currentMonth, 0)
    
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    // 设置可选日期范围
    const startDate = '2020-01-01'
    const endDate = formatDate(new Date())
    
    return {
      dateRange: [formatDate(firstDay), formatDate(lastDay)], // 默认选择当前月
      startDate: startDate, // 可选日期范围开始
      endDate: endDate, // 可选日期范围结束
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isRefreshing: false, // 是否正在下拉刷新
      loadMoreStatus: 'more', // 加载更多状态：more-加载前，loading-加载中，noMore-没有更多了
      incomeList: []
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    // 日期区间选择变更
    dateRangeChange(dateRange) {
      if (!dateRange || !dateRange.length) return;
      
      console.log('选择的日期区间:', dateRange);
      
      // 重置页码
      this.currentPage = 1;
      // 重新加载数据
      this.loadRecords(true);
    },
    
    // 下拉刷新
    onRefresh() {
      // 如果没有选择时间则不执行并且取消刷新
      if (!this.dateRange || !this.dateRange.length) {
        this.isRefreshing = false;
        return;
      }

      this.isRefreshing = true;
      this.currentPage = 1;
      this.loadRecords(true);
    },
    
    // 上拉加载更多
    loadMore() {
      if (this.loadMoreStatus !== 'more') return;
      
      this.currentPage++;
      this.loadMoreStatus = 'loading';
      this.loadRecords(false);
    },
    
    // 加载记录数据
    loadRecords(isReset = false) {
      if (!this.dateRange || !this.dateRange.length) return;
      
      // 如果不是刷新操作，则显示加载中
      if (!this.isRefreshing) {
        this.loadMoreStatus = 'loading';
      }
      
      // 构建请求参数
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        startTime: this.dateRange[0],
        endTime: this.dateRange[1],
        orderByColumn: 'transactionTime',
        isAsc: 'desc' 
      };
      
      // 调用接口获取数据
      selectIncomeExpenseList(params).then(res => {
        console.log('获取到的数据:', res);
        if (res.code == 200) {
          // 获取数据成功
          const records = res.rows || [];
          const total = res.total || 0;
          
          // 更新总数据量
          this.total = total;
          
          // 如果是重置数据（下拉刷新或日期变更），则替换数据
          if (isReset) {
            this.incomeList = records;
          } else {
            // 否则追加数据
            this.incomeList = this.incomeList.concat(records);
          }
          
          // 判断是否还有更多数据
          if (this.incomeList.length >= this.total) {
            this.loadMoreStatus = 'noMore';
          } else {
            this.loadMoreStatus = 'more';
          }
        } else {
          // 获取数据失败
          uni.showToast({
            title: res.msg || '获取收支明细失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('获取收支明细失败:', err);
        uni.showToast({
          title: '获取收支明细失败，请稍后重试',
          icon: 'none'
        });
      }).finally(() => {
        // 结束下拉刷新状态
        if (this.isRefreshing) {
          this.isRefreshing = false;
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.income-details-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  height: 90rpx;
  background-color: #4c9bfb;
  color: #fff;
  padding: 0 30rpx;
  position: relative;
}

.back-btn {
  position: absolute;
  left: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon-img {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
}

/* 日期选择区域 */
.date-picker-container {
  background-color: #fff;
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1px solid #eee;
}

/* 收支明细列表 */
.income-list {
  background-color: #fff;
  height: calc(100vh - 240rpx);
  padding: 0 30rpx;
}

/* 收支明细项 */
.record-item {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 0;
  border-bottom: 1px solid #eee;
}

.record-item:last-child {
  border-bottom: none;
}

.record-info {
  display: flex;
  flex-direction: column;
}

.record-amount {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.record-date {
  font-size: 24rpx;
  color: #999;
}

.record-status {
  font-size: 28rpx;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.income-amount {
  color: #e74c3c;
}

.expense-amount {
  color: #2ecc71;
}

.record-reason {
  font-size: 24rpx;
  color: #999;
  margin-top: 5rpx;
}

/* 加载状态 */
.loading-state {
  padding: 20rpx 0;
}
</style>